#!/usr/bin/env bash

# Filename     :	batch_add_user.sh
# Last modified:	2024-12-16 12:12
# Version      :
# Author       : jack.zang
# Email        : jack.zang@aishangwei.net
# Description  : 读取 user.txt 文件，生成一个匹配添加用户的 ldif 文件
#               ldapadd -x -W -D "cn=admin,dc=xiodi,dc=cn" -f ldap_entries.ldif
# 使用方法：
# ******************************************************

# File containing the list of names and their corresponding uids
input_file="user.txt"
output_file="ldap_entries.ldif"

# Clear output file
> "$output_file"

# Initialize uidNumber. Adjust this value based on your actual environment.
start_uid_number=2293

# Read each line in the input file
while IFS=' ' read -r full_name uid_with_hyphen; do
    # Skip empty lines
    [ -z "$full_name" ] && continue

    # Debugging output to check what's being read
    echo "Read line: Full Name = '$full_name', UID with hyphen = '$uid_with_hyphen'" >&2

    # Remove hyphen from uid for correct formatting
    uid=$(echo "$uid_with_hyphen" | tr -d '-')

    # Extract givenName and sn assuming the format is "FirstName LastName"
    # Note: This assumes that the name consists of two parts only.
    given_name=$(echo "$uid_with_hyphen" | cut -d'-' -f1)
    sn=$(echo "$uid_with_hyphen" | cut -d'-' -f2)

    # Generate a random password
    user_password=$(< /dev/urandom tr -dc 'a-zA-Z0-9' | head -c12)

    # Increment uidNumber for each new entry
    start_uid_number=$((start_uid_number + 1))

    # Write the LDIF entry to the output file
    {
        echo "dn: uid=${uid},ou=users,dc=xiodi,dc=cn"
        echo "objectClass: posixAccount"
        echo "objectClass: top"
        echo "objectClass: inetOrgPerson"
        echo "gidNumber: 0"
        echo "givenName: ${given_name}"
        echo "sn: ${sn}"
        echo "displayName: ${full_name}"
        echo "uid: ${uid}"
        echo "homeDirectory: /home/users/${uid}"
        echo "loginShell: /bin/bash"
        echo "cn: ${uid}"
        echo "uidNumber: ${start_uid_number}"
        echo "userPassword: ${user_password}"
        echo ""
    } >> "$output_file"
done < "$input_file"